<template>
  <div class="about">
    <!-- 顶部标题 -->
    <div class="header">
      <h1>🌡️ 实验室环境监测系统</h1>
      <p>实时监控温湿度数据 | 数据总数: {{ envData.count }}</p>
    </div>

    <!-- 主显示区域 -->
    <div class="main-content">
      <!-- 实时数据卡片 -->
      <div class="real-time-cards">
        <div class="data-card temperature-card">
          <div class="card-icon">🌡️</div>
          <div class="card-content">
            <h3>当前温度</h3>
            <div class="value" :class="getTempStatusClass(latestData.temperature)">
              {{ latestData.temperature }}°C
            </div>
            <div class="status" :class="getTempStatusClass(latestData.temperature)">
              {{ getTempStatusText(latestData.temperature) }}
            </div>
          </div>
        </div>

        <div class="data-card humidity-card">
          <div class="card-icon">💧</div>
          <div class="card-content">
            <h3>当前湿度</h3>
            <div class="value" :class="getHumidityStatusClass(latestData.humidity)">
              {{ latestData.humidity }}%
            </div>
            <div class="status" :class="getHumidityStatusClass(latestData.humidity)">
              {{ getHumidityStatusText(latestData.humidity) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 控制面板 -->
      <div class="control-panel">
        <div class="settings">
          <label>温度报警阈值：</label>
          <input 
            type="number" 
            v-model.number="tempThreshold" 
            min="0" 
            max="50"
            class="threshold-input"
          >
          <span>°C</span>

          <label>湿度报警阈值：</label>
          <input 
            type="number" 
            v-model.number="humidityThreshold" 
            min="0" 
            max="100"
            class="threshold-input"
          >
          <span>%</span>
        </div>

        <div class="control-buttons">
          <button @click="fetchEnvData" class="btn btn-refresh" :disabled="isLoading">
            {{ isLoading ? '加载中...' : '🔄 刷新数据' }}
          </button>
          <button @click="toggleAutoRefresh" class="btn" :class="autoRefresh ? 'btn-stop' : 'btn-start'">
            {{ autoRefresh ? '⏹️ 停止自动刷新' : '▶️ 开始自动刷新' }}
          </button>
        </div>
      </div>

      <!-- 报警状态 -->
      <div class="alarm-status" :class="{'alarm-active': hasAlarm}">
        <div class="alarm-icon">
          <span v-if="hasAlarm">🚨</span>
          <span v-else>✅</span>
        </div>
        <div class="alarm-info">
          <h3>{{ hasAlarm ? '环境异常警告！' : '环境状态正常' }}</h3>
          <p v-if="hasAlarm">{{ alarmMessage }}</p>
          <p v-else>所有参数均在安全范围内</p>
        </div>
        <button 
          v-if="hasAlarm" 
          @click="acknowledgeAlarm" 
          class="acknowledge-btn"
        >
          确认报警
        </button>
      </div>

      <!-- 数据表格 -->
      <div class="data-table">
        <h3>📊 历史数据记录</h3>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>温度 (°C)</th>
                <th>湿度 (%)</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr 
                v-for="item in envData.data" 
                :key="item.id"
                :class="getRowClass(item)"
              >
                <td>{{ item.id }}</td>
                <td :class="getTempStatusClass(item.temperature)">
                  {{ item.temperature }}°C
                </td>
                <td :class="getHumidityStatusClass(item.humidity)">
                  {{ item.humidity }}%
                </td>
                <td>
                  <span class="status-badge" :class="getRowStatusClass(item)">
                    {{ getRowStatusText(item) }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-cards">
        <div class="stat-card">
          <h4>🌡️ 温度统计</h4>
          <p>最高: <span class="stat-value">{{ stats.maxTemp }}°C</span></p>
          <p>最低: <span class="stat-value">{{ stats.minTemp }}°C</span></p>
          <p>平均: <span class="stat-value">{{ stats.avgTemp }}°C</span></p>
        </div>

        <div class="stat-card">
          <h4>💧 湿度统计</h4>
          <p>最高: <span class="stat-value">{{ stats.maxHumidity }}%</span></p>
          <p>最低: <span class="stat-value">{{ stats.minHumidity }}%</span></p>
          <p>平均: <span class="stat-value">{{ stats.avgHumidity }}%</span></p>
        </div>

        <div class="stat-card">
          <h4>📈 数据统计</h4>
          <p>总记录: <span class="stat-value">{{ envData.count }}</span></p>
          <p>正常: <span class="stat-value normal">{{ stats.normalCount }}</span></p>
          <p>异常: <span class="stat-value danger">{{ stats.abnormalCount }}</span></p>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>数据加载中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <p>❌ {{ error }}</p>
      <button @click="fetchEnvData" class="btn btn-retry">重试</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'EnvironmentMonitor',
  data() {
    return {
      envData: {
        data: [],
        count: 0
      },
      tempThreshold: 30,
      humidityThreshold: 80,
      isLoading: false,
      error: null,
      autoRefresh: false,
      autoRefreshInterval: null,
      alarmAcknowledged: false,
      refreshInterval: 5000 // 5秒自动刷新
    }
  },
  computed: {
    // 获取最新数据
    latestData() {
      return this.envData.data[0] || { temperature: 0, humidity: 0 };
    },
    
    // 检查是否有报警
    hasAlarm() {
      if (this.alarmAcknowledged) return false;
      return this.latestData.temperature > this.tempThreshold || 
             this.latestData.humidity > this.humidityThreshold;
    },
    
    // 报警消息
    alarmMessage() {
      const messages = [];
      if (this.latestData.temperature > this.tempThreshold) {
        messages.push(`温度过高: ${this.latestData.temperature}°C > ${this.tempThreshold}°C`);
      }
      if (this.latestData.humidity > this.humidityThreshold) {
        messages.push(`湿度过高: ${this.latestData.humidity}% > ${this.humidityThreshold}%`);
      }
      return messages.join(' | ');
    },
    
    // 统计信息
    stats() {
      const temps = this.envData.data.map(item => item.temperature);
      const humidities = this.envData.data.map(item => item.humidity);
      
      const maxTemp = Math.max(...temps);
      const minTemp = Math.min(...temps);
      const avgTemp = (temps.reduce((a, b) => a + b, 0) / temps.length).toFixed(1);
      
      const maxHumidity = Math.max(...humidities);
      const minHumidity = Math.min(...humidities);
      const avgHumidity = (humidities.reduce((a, b) => a + b, 0) / humidities.length).toFixed(1);
      
      let normalCount = 0;
      let abnormalCount = 0;
      
      this.envData.data.forEach(item => {
        if (item.temperature <= this.tempThreshold && item.humidity <= this.humidityThreshold) {
          normalCount++;
        } else {
          abnormalCount++;
        }
      });
      
      return {
        maxTemp: isFinite(maxTemp) ? maxTemp : 0,
        minTemp: isFinite(minTemp) ? minTemp : 0,
        avgTemp: isFinite(avgTemp) ? avgTemp : 0,
        maxHumidity: isFinite(maxHumidity) ? maxHumidity : 0,
        minHumidity: isFinite(minHumidity) ? minHumidity : 0,
        avgHumidity: isFinite(avgHumidity) ? avgHumidity : 0,
        normalCount,
        abnormalCount
      };
    }
  },
  methods: {
    // 获取环境数据
    async fetchEnvData() {
      this.isLoading = true;
      this.error = null;
      
      try {
        const response = await fetch('http://localhost:9000/env/all');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        if (result.code === 200) {
          this.envData = {
            data: result.data,
            count: result.count
          };
          this.checkAlarm();
        } else {
          throw new Error(result.msg || '获取数据失败');
        }
      } catch (err) {
        this.error = err.message;
        console.error('获取环境数据失败:', err);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 检查报警
    checkAlarm() {
      if (this.hasAlarm && !this.alarmAcknowledged) {
        this.triggerAlarm();
      }
    },
    
    // 触发报警
    triggerAlarm() {
      console.log('🚨 环境报警:', this.alarmMessage);
      
      // 浏览器通知
      if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('环境报警', {
          body: this.alarmMessage,
          icon: '🚨'
        });
      }
    },
    
    // 确认报警
    acknowledgeAlarm() {
      this.alarmAcknowledged = true;
    },
    
    // 切换自动刷新
    toggleAutoRefresh() {
      this.autoRefresh = !this.autoRefresh;
      
      if (this.autoRefresh) {
        this.autoRefreshInterval = setInterval(() => {
          this.fetchEnvData();
        }, this.refreshInterval);
      } else {
        if (this.autoRefreshInterval) {
          clearInterval(this.autoRefreshInterval);
          this.autoRefreshInterval = null;
        }
      }
    },
    
    // 温度状态相关方法
    getTempStatusClass(temp) {
      if (temp > this.tempThreshold) return 'danger';
      if (temp > this.tempThreshold - 5) return 'warning';
      return 'normal';
    },
    
    getTempStatusText(temp) {
      if (temp > this.tempThreshold) return '过高';
      if (temp > this.tempThreshold - 5) return '警告';
      return '正常';
    },
    
    // 湿度状态相关方法
    getHumidityStatusClass(humidity) {
      if (humidity > this.humidityThreshold) return 'danger';
      if (humidity > this.humidityThreshold - 10) return 'warning';
      return 'normal';
    },
    
    getHumidityStatusText(humidity) {
      if (humidity > this.humidityThreshold) return '过高';
      if (humidity > this.humidityThreshold - 10) return '警告';
      return '正常';
    },
    
    // 表格行样式
    getRowClass(item) {
      if (item.temperature > this.tempThreshold || item.humidity > this.humidityThreshold) {
        return 'abnormal-row';
      }
      return '';
    },
    
    getRowStatusClass(item) {
      if (item.temperature > this.tempThreshold || item.humidity > this.humidityThreshold) {
        return 'danger';
      }
      return 'normal';
    },
    
    getRowStatusText(item) {
      if (item.temperature > this.tempThreshold || item.humidity > this.humidityThreshold) {
        return '异常';
      }
      return '正常';
    }
  },
  mounted() {
    this.fetchEnvData();
    
    // 请求通知权限
    if ('Notification' in window) {
      Notification.requestPermission();
    }
  },
  beforeUnmount() {
    if (this.autoRefreshInterval) {
      clearInterval(this.autoRefreshInterval);
    }
  }
}
</script>

<style scoped>
.environment-monitor {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
}

.header h1 {
  margin: 0;
  font-size: 2.5rem;
}

.header p {
  margin: 0.5rem 0 0 0;
  opacity: 0.8;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.real-time-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
}

.data-card {
  background: rgba(255, 255, 255, 0.1);
  padding: 2rem;
  border-radius: 15px;
  display: flex;
  align-items: center;
  gap: 1rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-icon {
  font-size: 3rem;
}

.card-content h3 {
  margin: 0 0 0.5rem 0;
  opacity: 0.8;
}

.value {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0.5rem 0;
}

.status {
  font-size: 1rem;
  font-weight: bold;
}

/* 状态颜色 */
.normal { color: #2ed573; }
.warning { color: #ffa502; }
.danger { color: #ff4757; }

.control-panel {
  background: rgba(255, 255, 255, 0.1);
  padding: 1.5rem;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.settings {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.settings label {
  font-weight: bold;
}

.threshold-input {
  padding: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  width: 60px;
}

.control-buttons {
  display: flex;
  gap: 1rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-refresh {
  background: #2ed573;
  color: white;
}

.btn-start {
  background: #2ed573;
  color: white;
}

.btn-stop {
  background: #ff4757;
  color: white;
}

.btn-retry {
  background: #ffa502;
  color: white;
}

.alarm-status {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1.5rem;
  background: rgba(46, 213, 115, 0.2);
  border-radius: 10px;
  border: 2px solid #2ed573;
  transition: all 0.3s ease;
}

.alarm-active {
  background: rgba(255, 71, 87, 0.2);
  border-color: #ff4757;
  animation: alarmFlash 1s infinite;
}

@keyframes alarmFlash {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.alarm-icon {
  font-size: 2rem;
}

.acknowledge-btn {
  padding: 0.5rem 1rem;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.data-table {
  background: rgba(255, 255, 255, 0.1);
  padding: 1.5rem;
  border-radius: 10px;
}

.table-container {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  overflow: hidden;
}

th, td {
  padding: 1rem;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

th {
  background: rgba(255, 255, 255, 0.1);
  font-weight: bold;
}

.abnormal-row {
  background: rgba(255, 71, 87, 0.1);
}

.status-badge {
  padding: 0.3rem 0.8rem;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: bold;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

.stat-card {
  background: rgba(255, 255, 255, 0.1);
  padding: 1.5rem;
  border-radius: 10px;
}

.stat-card h4 {
  margin: 0 0 1rem 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 0.5rem;
}

.stat-value {
  font-weight: bold;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-top: 5px solid #2ed573;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  background: rgba(255, 71, 87, 0.2);
  padding: 1rem;
  border-radius: 8px;
  border: 1px solid #ff4757;
  text-align: center;
}

@media (max-width: 768px) {
  .control-panel {
    flex-direction: column;
    align-items: stretch;
  }
  
  .settings {
    justify-content: center;
  }
  
  .control-buttons {
    justify-content: center;
  }
  
  .real-time-cards,
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style>